package main

import (
	"context"
	"fmt"
	proto "go_rpc/grpc_validate_test/proto"
	"google.golang.org/grpc"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
	"net"
)

type Server struct {
	proto.UnimplementedGreeterServer
}

type Validator interface {
	Validate() error
}

func (s *Server) mustEmbedUnimplementedGreeterServer() {
	panic("implement me")
}

func (s *Server) SayHello(ctx context.Context, p *proto.Person) (*proto.Person, error) {
	return &proto.Person{
		Id:     p.Id,
		Email:  "2492343684@qq.com",
		Mobile: "13643424118",
	}, nil
}

func main() {
	// 实现拦截器
	interceptor := func(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp any, err error) {
		fmt.Println("接收到了一个新的请求")
		if r, ok := req.(Validator); ok {
			if err := r.Validate(); err != nil {
				// 内置常用状态码,使用codes
				return nil, status.Error(codes.InvalidArgument, err.Error())
			}
		} else {
			fmt.Printf("11111111111111111111111")
		}
		// 正常处理逻辑
		res, err := handler(ctx, req)
		if err != nil {
			fmt.Println("异常:", err.Error())
			panic(err)
		}
		fmt.Println("请求处理完成:")
		fmt.Println(res)
		return res, err
	}

	opt := grpc.UnaryInterceptor(interceptor)
	g := grpc.NewServer(opt)
	//修复错误
	proto.RegisterGreeterServer(g, &Server{})
	lis, err := net.Listen("tcp", "0.0.0.0:8080")
	if err != nil {
		panic("failed to listen: " + err.Error())
	}
	_ = g.Serve(lis)
}
